package com.freshman_registration.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.freshman_registration.pojo.Admins;
import com.freshman_registration.service.AdminService;
import com.freshman_registration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.List;

//用户控制器类
@RestController
@RequestMapping("/api/admin")
@Slf4j
public class AdminController {
    @Autowired
        private AdminService adminService;
    //添加用户信息
    @PostMapping("/insert")
        public Result<?> insertAdmin(@RequestBody Admins admin){
        return adminService.insertAdmin(admin);
    }
    //修改用户信息
    @PutMapping("/update")
            public Result<?> updateAdmin(@RequestBody Admins admin){

        return adminService.updateAdmin(admin);
    }
    //删除用户信息
   @DeleteMapping("/delete/{id}")
   public Result<?> deleteAdmin(@PathVariable Integer id){
        return adminService.deleteAdmin(id);
    }

   //分页查询所有用户
   @GetMapping("/queryAll")
   public Result<?> queryAllAdmins(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "5") Integer pageSize) {
       Page page = adminService.queryAllAdmins(currentPage, pageSize);
       PageInfo<Object> pageInfo = new PageInfo<>(page);
       return Result.success(pageInfo);
   }

   //验证码
   private LineCaptcha lineCaptcha;
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response) {
        lineCaptcha= CaptchaUtil.createLineCaptcha(125,45);
        lineCaptcha.setBackground(new Color(181,238,218));

        try{
            ServletOutputStream os =response.getOutputStream();
            lineCaptcha.write(os);
            os.flush();
            os.close();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    //用户登录
    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> admin) {
        //获取用户输入的验证码
        String code = admin.get("code");
        //验证码验证
        if (!lineCaptcha.verify(code)) {
            return Result.fail("验证码错误");
        }
        return adminService.login(admin.get("workNo"), admin.get("password"));
    }
//导出Excel
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        adminService.exportExcel(response);
    }

    /**
     * 文件导入模板
     * @param
     * @return
     * @throws IOException
     */
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        adminService.importTemplate(response);
    }

    @PostMapping("/import")
    public Result<?> importExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择要导入的Excel文件");
        }

        InputStream is = null;
        ExcelReader excelReader = null;
        int successCount = 0;
        int failCount = 0;
        StringBuilder errorMsg = new StringBuilder();

        try {
            // 获取输入流
            is = file.getInputStream();
            // 读取Excel
            excelReader = ExcelUtil.getReader(is);
            List<Admins> adminsList = excelReader.readAll(Admins.class);

            if (adminsList == null || adminsList.isEmpty()) {
                return Result.fail("Excel文件中没有数据");
            }

            for (Admins admin : adminsList) {
                try {
                    // 验证用户数据
                    if (admin.getUsername() == null || admin.getUsername().trim().isEmpty()) {
                        failCount++;
                        errorMsg.append("用户名不能为空; ");
                        continue;
                    }

                    Result<?> result = adminService.insertAdmin(admin);
                    if (result != null && "操作成功".equals(result.getMessage())) {
                        successCount++;
                    } else {
                        failCount++;
                        errorMsg.append("用户 <b>").append(admin.getUsername()).append("</b> 插入失败; ");
                    }
                } catch (Exception e) {
                    failCount++;
                    errorMsg.append("用户 <b>").append(admin.getUsername()).append("</b> 插入异常: ")
                            .append(e.getMessage()).append("; ");
                    // 记录详细异常日志
                    log.error("导入用户异常", e);
                }
            }

            // 构建返回结果
            if (failCount > 0) {
                return Result.success("数据导入完成，成功: <b>" + successCount + "</b>条，失败: <b>" + failCount + "</b>条。"
                        + errorMsg.toString());
            } else {
                return Result.success("数据导入成功，共导入" + successCount + "条记录");
            }

        } catch (IOException e) {
            log.error("Excel文件读取失败", e);
            return Result.fail("文件读取失败：" + e.getMessage());
        } finally {
            // 关闭资源
            if (excelReader != null) {
                try {
                    excelReader.close();
                } catch (Exception e) {
                    log.error("ExcelReader关闭失败", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("输入流关闭失败", e);
                }
            }
        }
    }


    //批量删除
    @DeleteMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestParam List<Integer> ids) {
        return adminService.deleteBatch(ids);
    }
    //状态更新
    @PutMapping("/admins/{id}/status")
    public Result<Integer> updateStatus(@PathVariable Integer id,
                                        @RequestBody Map<String,String> body) {
        String status = body.get("status");
        if (status == null) return Result.fail("status 不能为空");
        return adminService.updateStatus(id, status);
    }


    //根据状态或者用户名分页查询
    @GetMapping("/query")
    public Result<PageInfo<Admins>> queryAdmins(
            @RequestParam(defaultValue = "1") Integer currentPage,  // 前端传递的页码
            @RequestParam(defaultValue = "5") Integer pageSize,     // 前端传递的页大小
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer status) {

        // 调用修改后的Service方法（传递currentPage和pageSize）
        PageInfo<Admins> pageInfo = adminService.queryAdmins(status, username, currentPage, pageSize);
        return Result.success(pageInfo);
    }

    //更改密码
    @PutMapping("/updatePassword")
    public Result<?> updatePassword(@RequestBody Map<String, String> body) {
        Integer id = Integer.parseInt(body.get("id"));
        String password = body.get("password");
        return adminService.updatePassword(id, password);
    }

}
